#!/bin/bash

unset GIT_DIR

if [ ! -e "@CMAKE_SOURCE_DIR@/build" ]; then
	mkdir @CMAKE_SOURCE_DIR@/build
fi

if [ ! -d "@CMAKE_SOURCE_DIR@/build" ]; then
	echo "** The file, 'build', must be a directory"
	exit 1
fi

cd build

echo "-- Stashing un-staged changes"
git stash --keep-index > /dev/null 2>&1

echo "-- Testing project configuration"
cmake .. > CMakeConfigure.log

if [ $? != 0 ]; then
	echo "** Project failed to configure"
	git stash pop > /dev/null 2>&1
	exit 1
fi

echo "-- Project configures successfully"

echo "-- Testing project compilation"
cmake --build . > CMakeBuild.log

if [ $? != 0 ]; then
	echo "** Project failed to compile"
	git stash pop > /dev/null 2>&1
	exit 1
fi

echo "-- Project compiles successfully"

git stash pop > /dev/null 2>&1
echo "-- Stash is popped"

branch_name=$(git symbolic-ref HEAD 2>/dev/null)

if [ $? != 0 ]; then
	echo "** Failed to get current branch"
	exit 1
fi

if [ "$branch_name" = "refs/heads/master" ]; then
	echo "-- Running tests"

	ctest > CMakeTest.log 2>&1

	if [ $? != 0 ]; then
		echo "** Tests failed"
		exit 1
	fi

	echo "-- Tests passed"

elif [ "$branch_name" != "refs/heads/working" ]; then

	echo "** Unrecognized branch"
	exit 1
fi

exit 0

